package com.dingup.mock.module;

import com.dingup.mock.bean.exam.ExaminationInfo;
import com.dingup.util.GCookieUtil;
import com.dingup.util.GDateUtil;
import com.dingup.util.GDesEncryptUtil;
import org.apache.log4j.Logger;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

import static com.dingup.mock.util.ConstUtil.COOKIE_ITEM_EXAM_TOKEN_INFO;
import static com.dingup.mock.util.ConstUtil.EXAM_QUEUE_AUTO_CLEAR_EXPIRED_SECOND;

/**
 * Created by yanggavin on 25/02/2017.
 */
public class SExamCookieManager {
    private static class LazyHolder {
        private static final SExamCookieManager INSTANCE = new SExamCookieManager();
    }

    public static SExamCookieManager getInstance() {
        return SExamCookieManager.LazyHolder.INSTANCE;
    }

    private SExamCookieManager() {
    }

    private Logger logger = Logger.getLogger(SExamCookieManager.class);

    /**
     * 设置考试token信息cookie内容
     *
     * @param userId
     * @param examId
     * @return
     */
    public void setExamTokenCookie(HttpServletResponse response, String userId, String examId) {
        String cookieVal = GDesEncryptUtil.encryptData(
                String.format("%s,%s,%s", userId, examId, GDateUtil.getDateStr(new Date()))
        );
        GCookieUtil.addCookie(response, COOKIE_ITEM_EXAM_TOKEN_INFO, cookieVal, EXAM_QUEUE_AUTO_CLEAR_EXPIRED_SECOND);
    }

    /**
     * 删除考试token信息cookie内容
     *
     * @param response
     */
    public void delExamTokenCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie(COOKIE_ITEM_EXAM_TOKEN_INFO, null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    /**
     * 验证用户的考试Token的正确性
     *
     * @param request
     * @return
     */
    public Boolean checkExamTokenCookie(HttpServletRequest request) {
        boolean isPassed = false;
        try {
            Cookie cookie = GCookieUtil.getCookieByName(request, COOKIE_ITEM_EXAM_TOKEN_INFO);
            if (cookie != null) {
                String cv = GDesEncryptUtil.decryptData(cookie.getValue());
                String[] arr = cv.split(",");
                if (arr.length == 3) {
                    // 既要检查cookie数据是否过期，同时检查相应的考试ID是否有效.
                    if (!GDateUtil.checkExpired(GDateUtil.getDateFromStr(arr[2]), EXAM_QUEUE_AUTO_CLEAR_EXPIRED_SECOND)) {
//                        ExaminationInfo ei = (ExaminationInfo)SMemcachedManager.getInstance().get(arr[1].trim());
                        ExaminationInfo ei = new ExaminationInfo();
                        if (ei != null && ei.getUserId().equalsIgnoreCase(arr[0])) {
                            isPassed = true;
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("检查考试Token数据失败：" + e.getMessage());
        } finally {
            return isPassed;
        }
    }
}
